package com.jfinal.bbsapp.common.kit;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Map;
import org.apache.commons.beanutils.ConvertUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

public class RecordUtils {
	private static final Logger logger = LoggerFactory.getLogger(RecordUtils.class);
	
	/**
	 * Model 转 Record
	 * @param bean
	 * @return
	 */
	public static  Record converRecord(Model<?> model) { 
       Record r =new Record(); 
       r.setColumns(model); 
       return r;
	}
	
	/**
	 * Record 转 任意实例类
	 * @param type
	 * @param record
	 * @return
	 */
	public static <T> T converModel(Class<T> clazz,Record record){
		try {
			return	  convertMap(clazz, record.getColumns());
		} catch (Exception e) { 
			logger.error("Record 转 T 异常... ",e);
		} 
		return null;
	}
	
	public static <T> T convertMap(Class<T> type, Map<String, Object> map) throws Exception {
		T  obj = type.newInstance();		
		// 获取类属性
		BeanInfo beanInfo = Introspector.getBeanInfo(type);
		// 给 JavaBean 对象的属性赋值
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			if (map.containsKey(propertyName)) {
				String value = ConvertUtils.convert(map.get(propertyName));
				Object[] args = new Object[1];
				args[0] = ConvertUtils.convert(value, descriptor.getPropertyType());
				descriptor.getWriteMethod().invoke(obj, args);
			}
		}
		return obj;
	}
}
